package com.px.auth.util;

import com.px.auth.config.ApiSecurityConfig;
import com.px.common.core.RespCode;
import com.px.common.core.RespException;
import com.px.common.util.JsonUtil;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.MacSigner;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;

public class TokenUtil {
    public static Map getClaims(String token) throws RespException, Exception{
        if (StringUtils.isEmpty(token))
            throw new RespException(RespCode.TOKEN_ERROR, null);
        Jwt jwt = JwtHelper.decodeAndVerify(token, new MacSigner(ApiSecurityConfig.JWT_SIGNER_STR));
        Map claims = JsonUtil.fromJson(jwt.getClaims(), Map.class);
        long exp = Long.valueOf((String) claims.get("exp"));
        if (new Date().getTime() / 1000 > exp)
            throw new RespException(RespCode.TOKEN_EXPIRE, null);
        return claims;
    }
}
